package com.cn.kabalifeuser.ui.my.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.base.MyApplication;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.config.ShareUtil;
import com.cn.kabalifeuser.event.RxBus;
import com.cn.kabalifeuser.event.RxBusBean;
import com.cn.kabalifeuser.ui.integral.adapter.CommodityParamsAdapter;
import com.cn.kabalifeuser.ui.my.bean.InviteFriendsBean;
import com.cn.kabalifeuser.utils.BitmapUtil;
import com.cn.kabalifeuser.utils.GlideUtil;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.utils.Util;
import com.cn.kabalifeuser.view.PopupWindow.CommonPopupWindow;
import com.cn.kabalifeuser.view.PopupWindow.CommonUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 晓林 on 2020/9/24.
 * function: 邀请好友
 */
public class InviteFriendsActivtiy extends IBaseActivity<InviteFriendsView, InviteFriendsPresenter> implements InviteFriendsView, CommonPopupWindow.ViewInterface {
    @BindView(R.id.tv_in_no)
    TextView tvInNo;

    Bundle bundle;
    String Invite, Head, Nickname;
    @BindView(R.id.img_pic_arr_1)
    ImageView imgPicArr1;
    @BindView(R.id.img_pic_arr_check_1)
    ImageView imgPicArrCheck1;
    @BindView(R.id.img_pic_arr_2)
    ImageView imgPicArr2;
    @BindView(R.id.img_pic_arr_check_2)
    ImageView imgPicArrCheck2;

    int sign = 2;//默认是分享图片
    private CommonPopupWindow popupWindowShare;
    private CommonPopupWindow popupWindowShareImg;
    InviteFriendsBean inviteFriendsBean;
    int shareSign = 1;

    @Override
    protected InviteFriendsPresenter createPresenter() {
        return new InviteFriendsPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_invite_friends;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        bundle = getIntent().getExtras();
        Invite = bundle.getString("Invite");
        Head = bundle.getString("Head");
        Nickname = bundle.getString("Nickname");

        tvInNo.setText(Invite);
        imgPicArrCheck2.setImageResource(R.drawable.check_true);
        imgPicArrCheck1.setImageResource(R.drawable.check_false);
        sign = 2;
        mPresenter.onInviteFriendsData(LoginHelper.getLonginData().getResult());
    }

    @OnClick({R.id.tv_btn_copy, R.id.img_btn_left, R.id.ll_btn_share_url, R.id.ll_btn_share_img, R.id.img_pic_arr_1, R.id.img_pic_arr_2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_btn_copy:
                CopyToClipboard(this, tvInNo.getText().toString().trim());
                break;
            case R.id.img_btn_left:
                finish();
                break;
            case R.id.ll_btn_share_url:
                if (inviteFriendsBean != null) {
                    shareSign = 1;
                    showShare();
                }
                break;
            case R.id.ll_btn_share_img:
                if (inviteFriendsBean != null) {
                    shareSign = 2;
                    showShare();
                }
                break;
            case R.id.img_pic_arr_1:
                imgPicArrCheck1.setImageResource(R.drawable.check_true);
                imgPicArrCheck2.setImageResource(R.drawable.check_false);
                sign = 1;
                break;
            case R.id.img_pic_arr_2:
                imgPicArrCheck2.setImageResource(R.drawable.check_true);
                imgPicArrCheck1.setImageResource(R.drawable.check_false);
                sign = 2;
                break;
        }
    }


    private void showShare() {
        if (popupWindowShare != null && popupWindowShare.isShowing()) return;
        View upView = LayoutInflater.from(getMe()).inflate(R.layout.shape_img, null);
        //测量View的宽高
        CommonUtil.measureWidthAndHeight(upView);
        popupWindowShare = new CommonPopupWindow.Builder(getMe())
                .setView(R.layout.shape_img)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .create();
        popupWindowShare.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }

    /**
     * 主要方法：创建一个bitmap放于画布之上进行绘制 （简直如有神助）
     */
    private static Bitmap convertViewToBitmap(View tempView, Display disPlay) {
        Bitmap bitmap = Bitmap.createBitmap(tempView.getWidth(),
                tempView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        tempView.draw(canvas);
        return bitmap;
    }

    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            case R.layout.shape_img:
                ImageView img_bg = view.findViewById(R.id.img_bg);
                ImageView img_code = view.findViewById(R.id.img_code);
                LinearLayout ll_item = view.findViewById(R.id.ll_item);
                ImageView img_head = view.findViewById(R.id.img_head);
                TextView tv_name = view.findViewById(R.id.tv_name);
                GlideUtil.ImageLoad(getMe(), Head, img_head);
                tv_name.setText(Nickname);
                Glide.with(getMe())
                        .asBitmap()
                        .load(inviteFriendsBean.getResult().getPic_arr().get(sign == 1 ? 0 : 1).getImg())
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                img_bg.setImageBitmap(resource);
                            }
                        });
                Glide.with(getMe())
                        .asBitmap()
                        .load(inviteFriendsBean.getResult().getQrCode())
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                img_code.setImageBitmap(resource);
                            }

                        });
                view.findViewById(R.id.tv_wx).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (shareSign == 1) {
                            UMWeb umWeb = new UMWeb(inviteFriendsBean.getResult().getUrl());
                            umWeb.setTitle("分享链接标题");
                            //描述
                            umWeb.setDescription("分享链接描述");
                            umWeb.setThumb(new UMImage(InviteFriendsActivtiy.this, R.mipmap.ic_launcher));
//                            if (TextUtils.isEmpty(imageUrl)) {
//                                //本地缩略图
//                                umWeb.setThumb(new UMImage(activity, imageID));
//                            } else {
//                                //网络缩略图
//                                umWeb.setThumb(new UMImage(activity, imageUrl));
//                            }
                            ShareUtil.shareWXUrl(InviteFriendsActivtiy.this, umWeb);
                        } else {
                            //第一步：获取二进制图像的Bitmap对象
                            Bitmap bitmap = convertViewToBitmap(ll_item, null);
                            shareType(bitmap, 1);
//                            if (sign == 1)
//                                ShareUtil.shareWXImage(InviteFriendsActivtiy.this, bitmap);
//                            else
//                                ShareUtil.shareWXImage(InviteFriendsActivtiy.this, bitmap);

                        }
                        popupWindowShare.dismiss();
                    }
                });
                view.findViewById(R.id.tv_wx_p).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (shareSign == 1) {
                            UMWeb umWeb = new UMWeb(inviteFriendsBean.getResult().getUrl());
                            umWeb.setTitle("分享链接标题");
                            //描述
                            umWeb.setDescription("分享链接描述");
                            umWeb.setThumb(new UMImage(InviteFriendsActivtiy.this, R.mipmap.ic_launcher));
                            ShareUtil.shareWXManyUrl(InviteFriendsActivtiy.this, umWeb);
                        } else {
                            //第一步：获取二进制图像的Bitmap对象
                            Bitmap bitmap = convertViewToBitmap(ll_item, null);
                            shareType(bitmap, 2);
//                            if (sign == 1)
//                                ShareUtil.shareWXImageMany(InviteFriendsActivtiy.this, inviteFriendsBean.getResult().getPic_arr().get(0));
//                            else
//                                ShareUtil.shareWXImageMany(InviteFriendsActivtiy.this, inviteFriendsBean.getResult().getPic_arr().get(1));
                        }
                        popupWindowShare.dismiss();

                    }
                });
                view.findViewById(R.id.tv_url).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CopyToClipboard(getMe(), inviteFriendsBean.getResult().getUrl());
                        popupWindowShare.dismiss();

                    }
                });
                view.findViewById(R.id.tv_btn_next).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindowShare.dismiss();
                    }
                });
                break;
        }
    }

    private void shareType(Bitmap bitmap, int type) {
        // 第二步：创建WXImageObject，并包装bitmap
        WXImageObject imgObj = new WXImageObject(bitmap);
        //第三步：创建WXMediaMessage对象，并包装WXimageObjext对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        // 第四步：压缩图片
        Bitmap thumBitmap = bitmap.createScaledBitmap(bitmap, 120, 150, true);
        //释放图片占用的内存资源
        bitmap.recycle();
        msg.thumbData = Util.bmpToByteArray(thumBitmap, true);
        //第五步：创建SendMessageTo.Req对象，发送数据
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // 唯一标识
        req.transaction = buildTransaction("img");
        //发送的内容或者对象
        req.message = msg;
        req.scene = setType(type);
        MyApplication.mWxApi.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    //朋友和朋友圈
    private int setType(int type) {
        if (type == 1)
            return SendMessageToWX.Req.WXSceneSession;
        else return SendMessageToWX.Req.WXSceneTimeline;
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return null;
    }

    @Override
    public void onInviteFriendsSuccess(InviteFriendsBean bean) {
        inviteFriendsBean = bean;
        GlideUtil.ImageLoad(this, bean.getResult().getPic_arr().get(0).getCover(), imgPicArr1);
        GlideUtil.ImageLoad(this, bean.getResult().getPic_arr().get(1).getCover(), imgPicArr2);
    }


}
